const app = getApp();
Page({
  data: {
    array: ['请选择商品类型', '电子产品', '图书文娱', '生活用品', '鞋包服饰', '运动户外', '跑腿服务', '失物招领', '寻物启事', '其它', ],
    objectArray: [{
        id: 0,
        name: '电子产品'
      },
      {
        id: 1,
        name: '图书文娱'
      },
      {
        id: 2,
        name: '生活用品'
      },
      {
        id: 3,
        name: '鞋包服饰'
      },
      {
        id: 4,
        name: '运动户外'
      },
      {
        id: 5,
        name: '跑腿服务'
      },
      {
        id: 6,
        name: '失物招领'
      },
      {
        id: 7,
        name: '寻物启事'
      },
      {
        id: 8,
        name: '其它'
      }
    ],
    index: 0,
    numbers: 0,
    bflage: false,
    inputPrice: '',
    inputTitle: '',
    inputTrade: '',
    kind: -1,
    pathImg: ' ',
    temPath: [],
    thumb_id: '',
    titlevalue: null,
    pricevalue: null,
    areavalue: null,
    prompt: 0,
    isViolation: 0
  },
  copoint: function(price) {
    var counts = 0;
    var flag = false;
    var flag1 = false;
    var k = price.length;
    for (var i = 0; i <= price.length; i++) {
      if (price[i] == '.') {
        counts = counts + 1;
        k = i + 1;
        if (i == 0) {
          flag = true;
        }
      }
    }

    if ((price.length) - k > 2) {
      wx.showToast({
        title: '小数点后有效数字为两位',
        icon: 'none'
      })
      this.setData({
        inputPrice: ''
      })
    }
    if (counts > 1 || flag == true) {
      wx.showToast({
        title: '请输入正确的价格',
        icon: 'none'
      })
      this.setData({
        inputPrice: ''
      })
    }
  },
  bindPrice: function(e) {
    var price = e.detail.value;
    this.setData({
      inputPrice: e.detail.value
    })
    this.copoint(price);
  },
  bindTitle: function(e) {
    this.setData({
      inputTitle: e.detail.value
    })
  },
  bindTrade: function(e) {
    this.setData({
      inputTrade: e.detail.value
    })
  },
  pickerKind: function(e) {
    var flag = e.detail.value - 1;
    this.setData({
      kind: flag,
      index: e.detail.value
    })
  },

  onLoad: function(options) {
    var that = this;
    that.setData({
      numbers: 0,
      temPath: []
    })
    wx.setStorageSync('tempath', '');
  },

  onShow: function(options) {
    var is_Register = wx.getStorageSync('is_Register');
    app.globalData.isReturn = true;
    if (!is_Register) {
      wx.showModal({
        title: '友情提示',
        content: '请先注册',
        showCancel: false,
        success: res => {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/my/my',
            })
          }
        }
      })
    }
  },

  upimg: function(i, mid, imgId, user_id) {
    var that = this;
    var path = that.data.temPath;
    wx.uploadFile({
      url: app.globalData.targetUrl + 'upload/image/',
      filePath: that.data.temPath[i],
      name: 'img',
      header: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      formData: {
        'user_id': user_id
      },
      success: function(res) {
        var data = JSON.parse(res.data).data;
        var thumb_url = data.thumb_url;
        imgId.push(data.image_id);
        mid = mid + data.image_id + ";";
        that.setData({
          pathImg: mid,
          thumb_url: thumb_url
        })
      },
      complete: () => {
        i++;
        if (i == path.length) {
          var p1 = that.data.inputPrice;
          var p2 = parseFloat(p1).toFixed(2);
          that.setData({
            thumb_id: imgId[0],
            inputPrice: p2
          })
          var is_campus = wx.getStorageSync('is_campus');
          wx.request({
            url: app.globalData.targetUrl + "items/",
            header: {
              'Content-Type': 'application/x-www-form-urlencoded',
            },
            method: "POST",
            data: {
              user_id: user_id,
              is_campus: is_campus,
              type_id: that.data.kind,
              price: that.data.inputPrice,
              image_id: that.data.pathImg,
              content: that.data.inputTrade,
              title: that.data.inputTitle,
              thumbnail: that.data.thumb_url
            }, //给服务器传递数据
            success: function(res) {
              wx.hideLoading();
              if (res.data.error == 500) {
                wx.showToast({
                  title: '图片上传出现问题',
                  icon: 'none'
                })
              } else {
                var item_id = res.data.data.id;
                wx.showToast({
                  title: '上传完成',
                })
                wx.removeStorageSync("tempath");
                that.setData({
                  numbers: 0,
                  inputPrice: '',
                  inputTitle: '',
                  inputTrade: '',
                  titlevalue: null,
                  pricevalue: null,
                  areavalue: null,
                  temPath: '',
                  index: 0,
                  bflage: false,
                });
                // 添加发布记录
                wx.request({
                  url: app.globalData.targetUrl + 'history/item/',
                  method: 'POST',
                  header: {
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  data: {
                    'user_id': user_id,
                    'item_id': item_id,
                    'is_publish': 1
                  },
                  success: res => {
                    wx.navigateTo({
                      url: '/pages/history/publishhistory',
                    });
                  }
                });
              }
            }
          });
        } else {
          that.upimg(i, mid, imgId, user_id); //user_id
        }
      }
    })
  },

  submit: function(e) {
    var that = this;
    var formId = e.detail.formId;
    that.submitItem(formId);
    /*
    wx.getSetting({
      success(res) {
        if (!res.authSetting['setting.addFriend']) {
          wx.authorize({
            scope: 'setting.addFriend',
            success() {
              that.submitItem(formId);
            }
          })
        } else {
          
        }
      }
    })*/
  },


  //  发布 并收集formID
  submitItem: function(formId) {
    var that = this;
    var tempath = wx.getStorageSync("tempath");
    that.setData({
      bflage: true,
      msg_check: true,
      is_flag: 0
    })
    var user_id = wx.getStorageSync('user_id');
    app.saveFormId(user_id, formId); //创建formid
    var inputTitle = that.data.inputTitle;
    inputTitle = inputTitle.trim();
    var inputTrade = that.data.inputTrade;
    inputTrade = inputTrade.trim();
    if (inputTitle == '') {
      wx.showToast({
        title: '请核对商品标题',
        icon: 'none'
      })
      that.setData({
        bflage: false
      })
    } else if (that.data.kind == -1) {
      wx.showToast({
        title: '请核对商品类型',
        icon: 'none'
      })
      that.setData({
        bflage: false
      })
    } else if (that.data.inputPrice == '') {
      wx.showToast({
        title: '请核对商品价格',
        icon: 'none'
      })
      that.setData({
        bflage: false
      })
    } else if (inputTrade == '') {
      wx.showToast({
        title: '请核对商品描述',
        icon: 'none'
      })
      that.setData({
        bflage: false
      })
    } else if (tempath.length == 0) {
      wx.showToast({
        title: '请至少上传一张图片',
        icon: 'none'
      })
      that.setData({
        bflage: false
      })
    } else {
      that.onDetectionWord();
    }
    // 收集formID
    var user_id = wx.getStorageSync('user_id');
    app.saveFormId(user_id, formId);
  },



  //开始检测
  onDetectionWord: function() {
    var that = this;
    var str = that.data.inputTitle + that.data.inputTrade;
    that.isfindViolationStr(str);
  },

  //自定义匹配字段检测接口
  biddenStr: function(str) {
    var that = this;
    var forbiddenArray = ['代考', '代寝', '代课', 'daikao', 'daike', 'daiqin'];
    var re = '';
    for (var i = 0; i < forbiddenArray.length; i++) {
      if (i == forbiddenArray.length - 1)
        re += forbiddenArray[i];
      else
        re += forbiddenArray[i] + "|";
    }
    var pattern = new RegExp(re, "g");
    var judge = 0;
    if (pattern.test(str)) {
      judge = 1;
    }
    if (judge == 0) {
      wx.showLoading({
        title: '发布审核中',
      })
      that.finalSubmit();
    } else {
      console.log("44444")
      wx.showToast({
        title: '存在敏感词',
        icon: 'none',
        duration: 2000,
        success: res => {
          that.setData({
            bflage: false
          })
        }
      })
    }
  },

  //官方检测接口
  isfindViolationStr: function(str) {
    var that = this;
    wx.request({
      url: 'https://api.geek51.cn/wx/word/',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        'content': str
      },
      success: res => {
        if (res.data.error == 500) {
          wx.showToast({
            title: '存在敏感词',
            icon: 'none',
            duration: 1000,
            success: res => {
              that.setData({
                bflage: false
              })
            }
          })
        } else {
          that.biddenStr(str);
        }

      }
    })
  },

  //完成检测了，发布阶段
  finalSubmit: function() {
    var that = this;
    var imgId = [];
    var tempath = wx.getStorageSync("tempath");
    var numbers = tempath.length;
    that.setData({
      temPath: tempath,
      numbers: numbers,
    })
    var user_id = wx.getStorageSync('user_id'); //
    var i = 0;
    var mid = "";
    var path = that.data.temPath;
    that.upimg(i, mid, imgId, user_id); //user_id
  },
})